

// Promise支持异步

const PENDING = "PENDING"
const FULLFILLED = "FULLFILLED"
const REJECTED = "REJECTED"

function MyPromise(constructor){
    this.state = PENDING
    this.value = undefined
    this.reason = undefined
    this.onFullfilledCallbacks = new Array()
    this.onRejectedCallbacks = new Array()   

    const resolve = (value) =>{
       if(this.state === PENDING){
           this.state = FULLFILLED
           this.onFullfilledCallbacks.forEach(fn => {
                fn(value)
           })
           
       }
    }

    const reject = (reason) => {
        if(this.state === PENDING){
            this.state = REJECTED
            this.onRejectedCallbacks.forEach(fn => {
                fn(reason)
            })
        }
    }

    try {
        constructor(resolve, reject)
    } catch (error) {
        reject(error)
    }
   
}

MyPromise.prototype.then = function(onFullfilled, onRejected) {
    // 完成时的回调函数和失败时的回调函数没有定义时，给默认值
    onFullfilled = typeof onFullfilled === 'function'? onFullfilled : v => v
    onRejected = typeof onRejected === 'function'? onRejected : err => { new Error(err) }
    
    // 将then改成异步的,即将then传递的函数先保存到数组中，等到resolve的时候再执行
     //将resolved包裹到一个函数中push到数组中
    if(this.state === PENDING){
        this.onFullfilledCallbacks.push((value) => {
            onFullfilled(value)
        })
        this.onRejectedCallbacks.push((reason) => {
            onRejected(reason)
        })
    }else if(this.state === FULLFILLED){
        onFullfilled()
    }else if(this.state === REJECTED){
        onRejected()
    }
   
}

MyPromise.prototype.catch = function(onRejected){
   this.then(null, onRejected)
}

MyPromise.prototype.finally = function(){}

const p = new MyPromise((resolve, reject)=>{
    setTimeout(()=>{
        reject(123)
    }, 1000)
})
p.then((value)=>{
    console.log("Promise then", value)
})
p.catch((reason)=>{
    console.log("Promise catch", reason)
})



